package org.eden.heartbeat.api.jmx;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eden.heartbeat.api.Constants;
import org.eden.heartbeat.core.HeartbeatThread;
import org.eden.heartbeat.core.configuration.CoreApplicationConfiguration;
import org.eden.heartbeat.api.exception.ConfigurationException;
import org.eden.heartbeat.api.exception.ConfigurationNotFoundException;
import org.eden.heartbeat.api.model.MachineInfo;

/**
 * The core application that controls the thread that validates the machine status.
 *
 * @author trsimoes
 * @version $Revision:$
 */
public class HeartbeatCore implements HeartbeatCoreMBean {

    private static Log LOG = LogFactory.getLog(HeartbeatCore.class);

    private HeartbeatThread _thread = null;

    private MachineInfo machineInfo;

    public HeartbeatCore(MachineInfo machineInfo) {
        this.machineInfo = machineInfo;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getName() {
        return Constants.APP_NAME;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void start() {
        this._thread = new HeartbeatThread(machineInfo);
        this._thread.start();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void stop() {
        if (this._thread == null) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("HeartbeatCore thread was not started.");
            }
            this._thread = new HeartbeatThread(machineInfo);
        }
        this._thread.terminateExecution();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void reload() {
        try {
            CoreApplicationConfiguration.loadConfigurations();
            MachineInfo machineInfo = CoreApplicationConfiguration.getConfiguredRemoteMachine();
            this._thread.reload(machineInfo);
        } catch (ConfigurationException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("error loading configurations", e);
            }
        } catch (ConfigurationNotFoundException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("configuration not found", e);
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isRunning() {
        return this._thread == null || this._thread.isAlive();
    }
}